import { ref, reactive, getCurrentInstance } from 'vue'
import { tool } from "@/moduleExport"
import apiColumn from '@/api/org/sysStaffColumn'
import apiSysOptions from '@/api/org/sysOptions'

export const useSearch = (params) => {
    const {
        api,
        query = {},
    } = params

    const _query = Object.assign(reactive({
        pageNo: 1,
        pageSize: 50
    }), query)

    /**
     * 查询分页数据
     * @returns {Promise}
     */
    const pageData = ref([]) // 分页数据
    const doSearch = () => {
        if (!api && typeof api === 'function') {
            throw Error("api接口必传且必须是function")
        }

        return api(_query).then(res => {
            pageData.value = res
        })
    }

    /**
     * 查询不分页数据
     * @param {apiList:function} 查询接口
     * @returns {Promise}
     */
    const listData = ref([]) // 不分页数据
    const doSearchList = (apiList) => {
        if (!apiList && typeof apiList === 'function') {
            throw Error("不分页api接口必传且必须是function")
        }

        return apiList(_query).then(res => {
            listData.value = res
        })
    }

    /**
     * 获取表格列
     * @param {tableCode:String} 表格编码 
     * @returns {columns}
     */
    const getColumns = async (tableCode) => {
        if (!tableCode) {
            throw Error("表格编码必传")
        }

        const columns = await apiColumn.getByStaffId(tableCode)
        return columns
    }

    /**
     * 加载选项配置
     * @param {codeList:Array} map编码 
     * @returns {codeMap:Object}
     */
    const getCodeMap = async (codeList) => {
        if (!codeList && Array.isArray(codeList)) {
            throw Error("map编码必传且必须是Array")
        }

        const codeMap = await apiSysOptions.codeMap(codeList)
        return codeMap
    }


    /**
     * 复选框选中
     */
    const selection = ref([])// 复选框数据
    const selectChange = (list) => {
        selection.value = list
    }

    /**
     * 下载进度导出
     * @param {apiExportProgress} api接口
     * @param {queryExport} 查询条件
     * @param {stop} 前置条件,false表示停止查询
     * @returns {Promise}
     */
    const { proxy } = getCurrentInstance()
    const onExportProgress = (apiExportProgress, queryExport, stop) => {
        if (!apiExportProgress && typeof apiExportProgress === 'function') {
            throw Error("api接口必传且必须是function")
        }

        queryExport = queryExport || _query

        // 前置判断条件
        if (stop) {
            return
        }

        // 返回成功回调
        return new Promise(resolve => {
            tool().confirm('确认导出？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                tool().notify.info("正在导出")
                apiExportProgress(queryExport).then(() => {
                    proxy.$bus.emit(proxy.$busKey.openExportProgress)
                    resolve()
                })
            }).catch(() => { })
        })
    }

    /**
    * 禁启用
    * @param {apiDisabled} api接口
    * @param {queryDisabled} 查询条件
    */
    const toggleDisabled = (apiDisabled, ids, state) => {
        if (!api && typeof api === 'function') {
            throw Error("api接口必传且必须是function")
        }

        tool().confirm(state ? '是否确认禁用？' : '是否确认启用？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
            apiDisabled(ids, !state).then(() => {
                tool().notify.success("操作成功")
                doSearch()
            })
        }).catch(() => { })
    }

    /**
     * 合计
     * @param {param}  columns和data集合
     * @param {arr:Array} 统计的字段 
     * @param {tableClass:String} 表格class名，用于单页面多表格的区分
     * @returns {sums:Array} 合计结果
     */
    const getSummaries = (param, arr, tableClass) => {
        if (!arr && Array.isArray(arr)) {
            throw Error("统计的字段必传且必须是Array")
        }

        const { columns, data } = param
        if (columns.length == 0 || data.length == 0) {
            return []
        }
        const sums = []

        columns.forEach((column, index) => {
            if (index === 0) {
                sums[index] = '总计'
                return
            }
            //当前列是否在要求字段里
            if (!(column.property && arr.includes(column.property))) {
                return
            }
            //列的值
            const values = data.map(item => Number(item[column.property]))
            //求和
            if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr)
                    if (!isNaN(value)) {
                        return prev + curr
                    } else {
                        return prev
                    }
                }, 0)
                sums[index] = parseFloat(sums[index]).toFixed(2)
            } else {
                sums[index] = ''
            }

        })

        //合并行对齐
        const className = tableClass ? `.${tableClass} .el-table__footer-wrapper tr td` : '.el-table__footer-wrapper tr td'
        const tableFooterTr = document.querySelectorAll(className)
        tableFooterTr.forEach((e, index) => {
            e.width = columns[index]?.width
        })

        return sums
    }

    // 操作记录 #TODO

    return {
        doSearch, pageData,
        doSearchList, listData,
        selection, selectChange,
        getCodeMap,
        getColumns,
        onExportProgress,
        toggleDisabled,
        getSummaries
    }
}